package com.studentmanagement.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.studentmanagement.model.User;
import com.studentmanagement.service.UserService;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserService userService = new UserService();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 转发到登录页面
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        // 验证用户登录
        User user = userService.validateUser(username, password);
        
        if (user != null) {
            // 登录成功，将用户信息存入会话
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            
            // 重定向到首页
            response.sendRedirect(request.getContextPath() + "/dashboard.jsp");
        } else {
            // 登录失败，设置错误消息
            request.setAttribute("error", "用户名或密码错误");
            
            // 转发回登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}

